﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using ThridGroup.ERP.DTO.WarehouseManagement;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace ThridGroup.ERP.WarehouseManagement
{
    /// <summary>
    /// 外协入库服务实现
    /// </summary>
    public class OutsourcingWarehousingServices : ApplicationService, IOutsourcingWarehousingServices
    {
        private readonly IRepository<OutsourcingWarehousing, int> _outsourcingWarehousingrepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        public OutsourcingWarehousingServices(IRepository<OutsourcingWarehousing, int> outsourcingWarehousingrepository)
        {
            _outsourcingWarehousingrepository = outsourcingWarehousingrepository;
        }

        /// <summary>
        /// 新增外协入库
        /// </summary>
        /// <param name="createOutsourcingWarehousingDto">外协入库创建/编辑 DTO</param>
        /// <returns>1表示成功，0表示失败</returns>
        public async Task<int> AddOutsourcingWarehousingAsync(CreateOutsourcingWarehousingDto createOutsourcingWarehousingDto)
        {
            var entity = ObjectMapper.Map<CreateOutsourcingWarehousingDto, OutsourcingWarehousing>(createOutsourcingWarehousingDto);
            var result = await _outsourcingWarehousingrepository.InsertAsync(entity, true);
            return result == null ? 0 : 1;
        }

        /// <summary>
        /// 获取外协入库分页列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>数据列表和总条数</returns>
        public async Task<(List<OutsourcingWarehousingListDto> data, int total)> GetListAsync(QueryOutsourcingWarehousingDto query)
        {
            var queryable = await _outsourcingWarehousingrepository.GetQueryableAsync();

            // 过滤条件
            if (!string.IsNullOrWhiteSpace(query.InOrderCode))
            {
                queryable = queryable.Where(x => x.InOrderCode.Contains(query.InOrderCode));
            }

            if (!string.IsNullOrWhiteSpace(query.OutsourcedOrders))
            {
                queryable = queryable.Where(x => x.OutsourcedOrders.Contains(query.OutsourcedOrders));
            }

            if (!string.IsNullOrWhiteSpace(query.Vendor))
            {
                queryable = queryable.Where(x => x.Vendor.Contains(query.Vendor));
            }

            if (query.InOrderDate.HasValue)
            {
                var date = query.InOrderDate.Value.Date;
                queryable = queryable.Where(x => x.InOrderDate.Date == date);
            }

            // 总数
            var total = await queryable.CountAsync();

            // 分页
            var list = await queryable
                .OrderByDescending(x => x.Id)
                .Skip((query.Page - 1) * query.Limit)
                .Take(query.Limit)
                .Select(x => new OutsourcingWarehousingListDto
                {
                    Id = x.Id,
                    InOrderCode = x.InOrderCode,
                    InOrderName = x.InOrderName,
                    InOrderDate = x.InOrderDate,
                    OutsourcedOrders = x.OutsourcedOrders,
                    State = x.State,
                    PurchaseOrderCode = x.PurchaseOrderCode,
                    Vendor = x.Vendor,
                    InboundWarehouse = x.InboundWarehouse,
                    Remark = x.Remark
                })
                .ToListAsync();

            return (list, total);
        }

        /// <summary>
        /// 批量删除外协入库
        /// </summary>
        /// <param name="ids">要删除的ID集合</param>
        /// <returns>删除的记录数</returns>
        public async Task<int> BatchDeleteAsync(List<int> ids)
        {
            var entities = await _outsourcingWarehousingrepository.GetListAsync(x => ids.Contains(x.Id));
            await _outsourcingWarehousingrepository.DeleteManyAsync(entities);
            return entities.Count;
        }

        /// <summary>
        /// 修改单据状态
        /// </summary>
        /// <param name="id">外协入库主键ID</param>
        /// <param name="state">新状态</param>
        /// <returns>1表示成功，0表示未找到</returns>
        public async Task<int> UpdateStateAsync(int id, int state)
        {
            var entity = await _outsourcingWarehousingrepository.GetAsync(id);
            if (entity == null)
            {
                return 0;
            }
            entity.State = state;
            await _outsourcingWarehousingrepository.UpdateAsync(entity);
            return 1;
        }

        /// <summary>
        /// 根据ID获取外协入库详情（反填）
        /// </summary>
        /// <param name="id">外协入库主键ID</param>
        /// <returns>外协入库详情DTO</returns>
        public async Task<OutsourcingWarehousingListDto> GetByIdAsync(int id)
        {   
            var entity = await _outsourcingWarehousingrepository.GetAsync(id);
            return ObjectMapper.Map<OutsourcingWarehousing, OutsourcingWarehousingListDto>(entity);
        }

        /// <summary>
        /// 修改外协入库
        /// </summary>
        /// <param name="id">外协入库主键ID</param>
        /// <param name="dto">外协入库DTO</param>
        /// <returns>1表示成功，0表示未找到</returns>
        public async Task<int> UpdateAsync(int id, CreateOutsourcingWarehousingDto dto)
        {
            var entity = await _outsourcingWarehousingrepository.GetAsync(id);
            if (entity == null)
            {
                return 0;
            }
            ObjectMapper.Map(dto, entity);
            await _outsourcingWarehousingrepository.UpdateAsync(entity);
            return 1;
        }

        /// <summary>
        /// 删除单个外协入库
        /// </summary>
        /// <param name="id">外协入库主键ID</param>
        /// <returns>1表示成功，0表示未找到</returns>
        public async Task<int> DeleteAsync(int id)
        {
            var entity = await _outsourcingWarehousingrepository.GetAsync(id);
            if (entity == null)
            {
                return 0;
            }
            await _outsourcingWarehousingrepository.DeleteAsync(entity);
            return 1;
        }
    }
}
